const pagination = require("pagination"); //分页

module.exports = class extends think.Controller {

    async __before() {

        const adminId = await this.session('adminId');
        if (think.isEmpty(adminId)) {
            console.log("用户没有登录");
            await this.redirect('/admin/public/login');
        }

        const Administrator = this.mongoose('Administrator',{},'admin');
        if (think.isEmpty(adminId)) {
            this.fail(401, '/admin/public/login');
        }




        //系统管理员必须具备基本的系统管理权限
        // const {allowed, message} = await this.checkAccessPermission('manage_system', '用户不能维护系统后台', true);
        // await this.checkAccessPermission('manage_system', '用户不能维护系统后台', true);

        this.ctx.state.admin = {};

        const admin = await Administrator.findById(adminId).exec();
        if (admin) {
            delete admin.password;

            this.ctx.state.admin = admin;

            const Menu = this.mongoose('Menu', {}, 'admin');
            // const groups = await Menu.getMenuGroups();
            const groups = await Menu.distinct('group').exec();
            // console.log(groups)

            this.ctx.state.layout = {};
            let menu = [];
            for (let group of groups) {
                let item = {
                    group: group,
                    items: await Menu.getMenuByGroup(group)
                };
                menu.push(item);
            }

            this.ctx.state.layout.menu = menu;

        } else {
            this.fail(401, '/admin/public/login');
        }

    }

    async checkAccessPermission(code) {
        let allowed = await think.rbac.checkByCode(await this.session('adminId'), code, 'admin');
        return allowed;
    }

    // async checkAccessPermission(code, errmsg, forceLogin = false) {
    //     // console.log(this.session('adminId'));
    //     let allowed = await think.rbac.checkByCode(await this.session('adminId'), code, 'admin');
    //     if (!allowed && forceLogin) {
    //         this.forceLogin(errmsg);
    //     } else {
    //         return {code: allowed, message: errmsg};
    //     }
    // }

    // forceLogin(msg) {
    //     // this.redirect('/admin/public/login?err=' + encodeURI(msg));
    //     if (typeof msg === 'string') {
    //         this.redirect('/admin/public/login?err=' + encodeURI(msg));
    //     } else {
    //         this.redirect('/admin/public/login');
    //     }
    // }

    async changeModelField(model, id, field, value) {
        const Model = this.model(model);
        let update = {};
        update[field] = value;
        await Model.findByIdAndUpdate(id, update).exec();
    }

    async isLogin() {
        const adminId = await this.session('adminId');
        return !think.isEmpty(adminId);
    }


    ajaxPage(current, total, perPage, get_page) {
        perPage = perPage || 25;
        get_page = get_page || 'get_page';


        const page = new pagination.TemplatePaginator({
            prelink: '', current: current, rowsPerPage: perPage,
            totalResult: total,
            template: function (result) {
                let i, len;
                let html = '<div><ul class="pagination no-margin">';
                if (result.pageCount < 2) {
                    html += '<li><a style="background: #fff;">共 ' + total + ' 条记录  1/1 页</a></li>';
                    html += '</ul></div>';
                    return html;
                }
                if (result.previous) {
                    html += `<li><a href="javascript:${get_page}(${result.previous })" style="background: #fff;">上一页</a></li>`;
                }
                if (result.range.length) {
                    for (i = 0, len = result.range.length; i < len; i++) {
                        if (result.range[i] === result.current) {
                            html += `<li class="active"><a href="javascript:${get_page}(${result.range[i]})" style="border-color: #dd4b39;background-color: #dd4b39;">${result.range[i]}</a></li>`;
                        } else {
                            html += `<li><a href="javascript:${get_page}(${result.range[i]})" style="background: #fff;">${result.range[i]}</a></li>`;
                        }
                    }
                }
                if (result.next) {
                    html += `<li><a href="javascript:${get_page}(${result.next})" class="paginator-next" style="background: #fff;">下一页</a></li>`;
                }
                html += '</ul></div>';
                return html;
            }
        });
        return page.render();
    }
};
